<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/2/18
 * Time: 13:03
 */

namespace app\admin\controller;


use app\admin\model\ChannelList;
use app\admin\model\Participant;
use app\admin\model\ReportLog;
use app\admin\model\VoteList;
use think\Config;

class Report extends Admin
{
    protected $code_name = '报表';

    public function set_param(){
        parent::set_param();
        $this->assign('code','report');
        $this->assign('code_name',$this->code_name);
    }

    public function index(){
        $params = $this->request->param();
        if(empty($params['active_id'])){
            $this->error('活动id丢失');
        }
        $active_id = $params['active_id'];
        $participant_id = empty($params['participant_id'])?'':$params['participant_id'];
        $params['dates'] = empty($params['dates'])?'':$params['dates'];
        $params['date'] = empty($params['date'])?'':$params['date'];
        $params['start_time'] = empty($params['start_time'])?'':$params['start_time'];
        $params['end_time'] = empty($params['end_time'])?'':$params['end_time'];
        $dates = ['today'=>'今日','yesterday'=>'昨日',7=>'最近7日',15=>'最近15日',30=>'最近30日','other'=>'选择某一日','other2'=>'选择时间段'];
        $report_data = [];
        $array = ['active_id'=>$active_id,'participant_id'=>$participant_id];
        //获取数据
        if( !empty($params['dates']) && in_array($params['dates'],[7,15,30,'other2'])){
            if($params['dates'] == 'other2'){
                if(empty($params['start_time']) || empty($params['end_time'])){
                    $this->error('时间段选择不完整');
                }
                if($params['start_time']){
                    $array['start_time'] = strtotime($params['start_time'].' 00:00:00');
                }
                if($params['end_time']){
                    $array['end_time'] = strtotime($params['end_time'].' 23:59:59');
                    if(date('Y-m-d') == $params['end_time']){
                        //结束时间为今天的的话往前一天;
                        $array['end_time'] -= 86400;
                    }
                    if($array['end_time']>time()){
                        $this->error('结束日期不正确');
                    }
                }
                if($array['end_time']-$array['start_time'] > 86400*40){
                    $this->error('时间段选择区间过大,最多40天');
                }
            }
            $array['other_day'] = $params['dates'];

            $result = $this->other_day($array);
            $chart = json_encode(['time'=>$result['time'],'series'=>$result['series']]);
        }else{
            if($params['dates'] == 'yesterday'){
                $array['today'] = strtotime(date('Y-m-d',time()-86400).' 23:59:59');
            }else if($params['dates'] == 'other'){
                $array['today'] = strtotime($params['date'].' 23:59:59');
            }

            $result = $this->today($array);
            //print_r($result);die;
            $chart = json_encode(['time'=>$result['time'],'series'=>$result['series']]);
        }

        $pass_way = Config::get('pass_way');
        $channel = ChannelList::column('channel_name','id');
        foreach($result['vote_pass_way'] as $key=>$value){
            $report_data['投票人来源-'.$pass_way[$key]] = $value;
        }
        /*foreach($result['vote_channel'] as $key=>$value){
            $report_data['投票人微信渠道-'.$channel[$key]] = $value;
        }*/
        if(!empty($result['participant_pass_way'])){
            foreach($result['participant_pass_way'] as $key=>$value){
                $report_data['参与人来源-'.$pass_way[$key]] = $value;
            }
        }
        /*if(!empty($result['participant_channel'])){
            foreach($result['participant_channel'] as $key=>$value){
                $report_data['参与人微信渠道-'.$channel[$key]] = $value;
            }
        }*/

        //12小时内票最多的10个人,没有participant_id才查询
        $list = $users = [];
        if(!$participant_id){
            $list = VoteList::field('count(*) as count,participant_id')->where('active_id',$active_id)->where('create_time','>',time()-43200)->where('status',1)
                ->group('participant_id')->order('count desc')->limit(10)->select();
            $user_ids = [];
            if ($list){
                foreach($list as $value){
                    $user_ids[] = $value->participant_id;
                }
                $users = Participant::where('active_id',$active_id)->where('user_id','in',$user_ids)->column('nickname','user_id');
            }

        }

        //渲染视图
        return view('',['chart'=>$chart,'dates'=>$dates,'active_id'=>$active_id,'selected'=>$params['dates'],
            'date'=>$params['date'],'report_data'=>$report_data,'participant_id'=>$participant_id,'list'=>$list,'users'=>$users,
        'start_time'=>$params['start_time'],'end_time'=>$params['end_time']]);
    }

    /**
     * 获得今天或者某一天的结果
     * @param $params
     * @return array
     */
    private function today($params){
        if (empty($params['today'])){
            $now_time = time();
            //今日最早的一个时间戳
            $before_time = strtotime(date('Y-m-d',$now_time).' 00:00:00');
            $timestamp_array = [];

            for($i=$before_time;$i<=$now_time;$i+=3600){
                $timestamp_array[date('G时',$i)] = $i;
            }
            //设置查询条件
            $where['create_time']=['between',[$before_time,$now_time]];
            $where['active_id']=['=',$params['active_id']];
            $where['status']=['=',1];
            if(!empty($params['participant_id'])){
                $where['participant_id'] = $params['participant_id'];
            }
            $result = $this->select_result($timestamp_array,$where,empty($params['participant_id'])?false:true);
        }else{
            $now_time = $params['today'];
            $has_participant_id = empty($params['participant_id'])?false:true;
            $log_where['date_name'] = date('Y-m-d',$params['today']);
            if ($has_participant_id){
                $log_where['participant_id'] = $params['participant_id'];
            }else{
                $log_where['participant_id'] = '';
            }
            $log_model = new ReportLog();
            $res = $log_model->where($log_where)->find();
            if (empty($res)){
                $before_time = strtotime(date('Y-m-d',$now_time).' 00:00:00');
                $timestamp_array = [];

                for($i=$before_time;$i<=$now_time;$i+=3600){
                    $timestamp_array[date('G时',$i)] = $i;
                }
                //设置查询条件
                $where['create_time']=['between',[$before_time,$now_time]];
                $where['active_id']=['=',$params['active_id']];
                $where['status']=['=',1];
                if(!empty($params['participant_id'])){
                    $where['participant_id'] = $params['participant_id'];
                }
                $result = $this->select_result($timestamp_array,$where,$has_participant_id);
                ReportLog::create([
                    'act_id'=>$params['active_id'],
                    'date_name'=>date('Y-m-d',$params['today']),
                    'vote_channel'=>$result['vote_channel'],
                    'vote_pass_way'=>$result['vote_pass_way'],
                    'series'=>$result['series'],
                    'participant_channel'=>!empty($result['participant_channel'])?$result['participant_channel']:'',
                    'participant_pass_way'=>!empty($result['participant_pass_way'])?$result['participant_pass_way']:'',
                    'time'=>$result['time'],
                    'participant_id'=>$has_participant_id?$params['participant_id']:'',
                ]);
            }else{
                $result = $res->toArray();
            }

        }

        return $result;
    }

    /**
     * 获得前几天的结果
     * @param $params
     * @return array
     */
    private function other_day($params){

        if(empty($params['end_time'])){
            $now_time = time()-86400;
        }else{
            $now_time = $params['end_time'];
        }

        //最早的一个时间戳
        if(empty($params['start_time'])){
            $before_time = strtotime(date('Y-m-d',$now_time-86400*($params['other_day']-1)).' 00:00:00');
        }else{
            $before_time = $params['start_time'];
        }

        $dates = [];

        for($i=$before_time;$i<=$now_time;$i+=86400){
            $dates[date('Y-m-d',$i)] = date('n月j日',$i);
        }
        $has_participant_id = empty($params['participant_id'])?false:true;
        $log_where['date_name'] = ['in',array_keys($dates)];
        if ($has_participant_id){
            $log_where['participant_id'] = $params['participant_id'];
        }else{
            $log_where['participant_id'] = '';
        }
        $log_model = new ReportLog();
        $res = $log_model->where($log_where)->order('date_name asc')->select();

        $vote_channel = $participant_channel =  $time = [];
        $series = [['name'=>'投票人数']];
        $vote_pass_way = ['wx'=>0,'yqsbz'=>0];
        $participant_pass_way =['wx'=>0,'yqsbz'=>0,'backend'=>0];
        foreach($res as $item){
            $time[] = $dates[$item->date_name];
            $series[0]['data'][] = array_sum($item->series[0]['data']);
            $vote_pass_way['wx'] += $item->vote_pass_way['wx'];
            $vote_pass_way['yqsbz'] += $item->vote_pass_way['yqsbz'];
            if(!$has_participant_id){
                $series[1]['data'][] = array_sum($item->series[1]['data']);
                $participant_pass_way['wx'] += $item->participant_pass_way['wx'];
                $participant_pass_way['yqsbz'] += $item->participant_pass_way['yqsbz'];
                $participant_pass_way['backend'] += $item->participant_pass_way['backend'];
            }
        }
        $result = [
            'vote_channel'=>$vote_channel,
            'vote_pass_way'=>$vote_pass_way,
            'time'=>$time
        ];
        if(!empty($series[1]['data'])){
            $series[1]['name'] = '参与人数';
            $result['participant_channel'] = $participant_channel;
            $result['participant_pass_way'] = $participant_pass_way;
        }
        $result['series'] = $series;
        return $result;

        //设置查询条件
        /*$where['create_time']=['between',[$before_time,$now_time]];
        $where['active_id'] = $params['active_id'];
        $where['status']=['=',1];
        if(!empty($params['participant_id'])){
            $where['participant_id'] = $params['participant_id'];
        }
        return $this->select_result($timestamp_array,$where,empty($params['participant_id'])?false:true,86400)*/;
    }

    private function select_result($timestamp_array,$where,$p=false,$t=3600){
        //查询投票表
        //先建立一个跟时间段相同长度值为0的数组,以防数据不完整无法有正确结果返回
        $vote_number = $vote_channel = [];
        $vote_pass_way = ['wx'=>0,'yqsbz'=>0];
        for($i = 0; $i < count($timestamp_array); $i++){
            $vote_number[$i] = 0;
        }

        $vote_list = VoteList::field('id,active_id,status,participant_id,from_pass_way,channel,create_time')->where($where)->select();
        if($vote_list){
            foreach($vote_list as $item){
                $vote_pass_way[$item->from_pass_way]++;
                if($item->from_pass_way != 'yqsbz'){
                    if(empty($vote_channel[$item->channel])){
                        $vote_channel[$item->channel] = 1;
                    }else{
                        $vote_channel[$item->channel]++;
                    }
                }
                $item_create_time = $item->create_time;
                foreach(array_values($timestamp_array) as $k=>$timestamp){
                    if($timestamp+$t < $item_create_time){
                        continue;
                    }else{
                        $vote_number[$k]++;
                        break;
                    }
                }
            }
        }
        $result = [
            'vote_channel' => $vote_channel,
            'vote_pass_way' => $vote_pass_way,
            'series'=>[['name'=>'投票人数','data'=>$vote_number]]
        ];

        if($p === false){
            //查询参赛表
            $participant_number = $participant_channel = [];
            for($i = 0; $i < count($timestamp_array); $i++){
                $participant_number[$i] = 0;
            }
            $participant_pass_way = ['wx'=>0,'yqsbz'=>0,'backend'=>0];

            $participant_list = Participant::where($where)->select();
            if($participant_list){
                foreach($participant_list as $item){
                    $participant_pass_way[$item->sign_pass_way]++;
                    if($item->sign_pass_way != 'yqsbz'){
                        if(empty($participant_channel[$item->channel])){
                            $participant_channel[$item->channel] = 1;
                        }else{
                            $participant_channel[$item->channel]++;
                        }
                    }

                    $item_create_time = $item->create_time;
                    foreach(array_values($timestamp_array) as $k=>$timestamp){
                        if($timestamp+$t < $item_create_time){
                            continue;
                        }else{
                            $participant_number[$k]++;
                            break;
                        }
                    }
                }
            }
            $result['participant_channel'] = $participant_channel;
            $result['participant_pass_way'] = $participant_pass_way;
            $result['series'][] = ['name'=>'参与人数','data'=>$participant_number];
        }
        $result['time'] = array_keys($timestamp_array);

        return $result;
    }
}